package com.chinaunicom.emergency.action;

import com.chinaunicom.emergency.annotation.Permission;
import com.chinaunicom.emergency.model.Permissions;
import com.chinaunicom.emergency.repository.PermissionsRepository;
import com.chinaunicom.emergency.service.PermissionService;
import com.chinaunicom.emergency.service.RoleService;
import com.chinaunicom.emergency.util.Assert;
import com.chinaunicom.emergency.util.UpdateUtil;
import com.chinaunicom.emergency.exception.CheckException;
import com.chinaunicom.emergency.repository.RolePermissionsRepository;
import com.chinaunicom.emergency.repository.RoleRepository;
import com.chinaunicom.emergency.repository.UserRoleRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liliang
 * @Date 2019/12/18 15:22
 * @Version 1.0
 */
@RestController
@Api(tags = {"权限管理"})
@RequestMapping("/api/permission")
@Log4j2
@RefreshScope
public class PermissionAction extends BaseAction {
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    UserRoleRepository userRoleRepository;
    @Autowired
    RolePermissionsRepository rolePermissionsRepository;
    @Autowired
    PermissionService permissionService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionsRepository permissionsRepository;


    @ApiOperation("权限资源新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("permission:add")
    @PostMapping(value = "/add")
    public Object add(@RequestBody Permissions permissions) throws CheckException {
        Assert.isBlank(permissions.getPermissionsCode(), "权限编码不能为空");
        Assert.isBlank(permissions.getPermissionsCn(), "权限名称不能为空");
        Assert.isBlank(permissions.getAppkey(), "权限所属分类不能为空");

        List<Permissions> existPermissionList = permissionsRepository.findByParentIdAndAppkeyAndPermissionsCodeAndIsSoftDel
                (permissions.getParentId(),permissions.getAppkey(),permissions.getPermissionsCode(),0);
        Assert.isNotNull(existPermissionList,permissions.getAppkey()+"下同一节点下权限编码重复,请勿重复创建");
        permissions.setIsSoftDel(0);
        permissions.setCreateBy(getCurrUserId());
        permissions.setCreateTime(new Date());
        permissionsRepository.save(permissions);
        return success();
    }

    @ApiOperation("权限资源修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("permission:update")
    @PutMapping(value = "/update")
    public Object update(@RequestBody Permissions permissions) throws CheckException {
        Assert.isBlank(permissions.getPermissionsCode(), "权限编码不能为空");
        Assert.isBlank(permissions.getPermissionsCn(), "权限名称不能为空");
        Assert.isBlank(permissions.getAppkey(), "权限所属分类不能为空");
        Permissions oldPermissions = permissionsRepository.findByPidAndIsSoftDel(permissions.getPid(),0);
        Assert.isNull(oldPermissions,"该权限资源不存在,修改失败");
        Assert.isNotEquals(permissions.getAppkey(),oldPermissions.getAppkey(),"权限所属分类无法修改");
        Assert.isNotEquals(permissions.getParentId(),oldPermissions.getParentId(),"权限上级节点无法修改");
        List<Permissions> existPermissionList = permissionsRepository.findByParentIdAndAppkeyAndPermissionsCodeAndIsSoftDel
                (permissions.getParentId(),permissions.getAppkey(),permissions.getPermissionsCode(),0);
        if(!CollectionUtils.isEmpty(existPermissionList)){
            Assert.isNotEquals(existPermissionList.get(0).getPid(),permissions.getPid(),permissions.getAppkey()+"下同一节点下权限编码重复,请勿重复创建");
        }
        permissions.setUpdateBy(getCurrUserId());
        permissions.setUpdateTime(new Date());
        UpdateUtil.copyNullProperties(oldPermissions,permissions);
        permissionsRepository.save(permissions);
        return success();
    }

    @ApiOperation("权限资源删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("permission:delete")
    @DeleteMapping(value = "/delete")
    public Object delete(@RequestParam(value = "pid") String pid) throws CheckException {
        Assert.isBlank(pid, "权限资源id不能为空");
        Permissions thisPermissions = permissionsRepository.findByPidAndIsSoftDel(pid,0);
        Assert.isNull(thisPermissions,"该权限资源不存在,删除失败");
        //权限是否关联了角色
        List<String> rolePerList = rolePermissionsRepository.findRoleNameByPermissionId(pid);
        Assert.isNotNull(rolePerList,"该资源权限已关联角色,无法删除");

        thisPermissions.setDeleteBy(getCurrUserId());
        thisPermissions.setIsSoftDel(1);
        thisPermissions.setDeleteTime(new Date());
        permissionsRepository.save(thisPermissions);
        return success();
    }


    @ApiOperation("单个资源权限明细查看")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("permission:detail")
    @GetMapping(value = "/{pid}")
    public Object findByPid(@PathVariable String pid) throws CheckException {
        Assert.isBlank(pid, "资源权限id不能为空");
        Permissions permissions = permissionsRepository.findByPidAndIsSoftDel(pid,0);
        return success(permissions);
    }

    @ApiOperation("根据pid分页查看资源权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "token", required = true, dataType = "String", paramType = "header")
    })
    @Permission("permission:page")
    @GetMapping(value = "/page")
    public Object findPage(@RequestParam(value = "limit", required = false) Integer limit,
                           @RequestParam(value = "page", required = false) Integer page,
                           @RequestParam(value = "parentId", required = false) String parentId,
                           @RequestParam(value = "appkey", required = false) String appkey
    ) throws CheckException {
        Map<String, Object> para = new HashMap<>();
        para.put("limit", limit == null ? 10 : limit);
        para.put("page", page == null ? 1 : page);
        para.put("isSoftDel", 0);
        para.put("parentId",parentId);
        para.put("appkey",appkey);
        Sort sort = Sort.by(Sort.Direction.ASC, "appkey","parentId","orderId");
        Page<Permissions> pages = permissionsRepository.findAll(permissionService.findPageByCondition(para), getPageable(para, sort));

        return page(pages);
    }
    
    @ApiOperation("获取所有资源")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "authorization", value = "token", required = true, paramType = "header", dataType = "String")})
    @Permission("permission:all")
    @GetMapping(value = "/all")
	public Object getOrgAll() throws CheckException {
	    List<Permissions> orgList = permissionsRepository.findAllByIsSoftDel(0);
//	    if(!CollectionUtils.isEmpty(orgList)){
//	        orgList.forEach(org ->{
//	            org.setOrgNameStr((String)redisService.getHash(ConstantUtil.PREFIX_ORG_TREE+":ORGID_NAMESTR",org.getOrgId()));
//	        });
//	    }
	    return success(orgList);
	}


}
